package com.net.model.https;

import com.net.model.interceptor.HttpLogInterceptor;
import com.net.model.interceptor.TokenInterceptor;
import com.net.model.utils.Constant;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 版权：周和权 版权所有
 *
 * @author zhouhequan
 * 版本：1.0
 * 创建日期：2021/11/12 or 22:35
 * 描述：---
 */
public class RequetRetrofit {
    private static RequetRetrofit instance;
    /**
     * 创建Retrofit相关对象
     */
    private static Retrofit retrofit;
    public final static int CONNECT_TIMEOUT = 30;
    public final static int READ_TIMEOUT = 30;
    public final static int WRITE_TIMEOUT = 30;

    public static RequetRetrofit getInstance() {
        if (instance == null) {
            synchronized (RequetRetrofit.class) {
                if (instance == null) {
                    instance = new RequetRetrofit();
                }
            }
        }
        return instance;
    }

    public RequetRetrofit() {
        createRetrofit();
    }


    public void createRetrofit() {
        OkHttpClient okBuilder = createOkHttpClient();
        retrofit = new Retrofit.Builder()
                .client(okBuilder)                       //请求的网络框架
                .baseUrl(Constant.releaseServer)         //BaseUrl
//                .addConverterFactory(new NullOnEmptyConverterFactory())
                .addConverterFactory(new BooleanConverterFactory())
                .addConverterFactory(GsonConverterFactory.create())     //解析数据格式
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // 使用RxJava作为回调适配器
                .build();
    }

    private OkHttpClient createOkHttpClient() {
        return new OkHttpClient.Builder()
//                .addInterceptor(new BasicAuthInterceptor())
//                .addInterceptor(new VersionInterceptor())
                .addInterceptor(new TokenInterceptor())
                .addInterceptor(new HttpLogInterceptor())
                .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)//设置请求超时时间
                .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)//设置写入超时时间
                .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间
                .retryOnConnectionFailure(true)//设置出现错误进行重新连接
                .build();
    }

    public <T> T getRetrofit(final Class<T> service) {
        return retrofit.create(service);
    }
}
